package com.njworkorder.HTSingleLogin;

import java.io.InputStream;
import java.util.*;

import cn.microvideo.qsc.client.api.QsApi;
import cn.microvideo.qsc.client.entity.Role;
import cn.microvideo.qsc.client.entity.xml.ParentRoles;
import cn.microvideo.qsc.client.entity.xml.Roles;
import cn.microvideo.qsc.client.utils.BasecodeUtil;
import cn.microvideo.qsc.client.utils.InputStreamHelper;
import cn.microvideo.qsc.client.utils.RequestMethod;
import cn.microvideo.qsc.client.utils.SAXHelper;

import com.thoughtworks.xstream.XStream;
import com.thoughtworks.xstream.io.xml.DomDriver;
import lombok.extern.slf4j.Slf4j;
import org.dom4j.Document;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;

/**
 * 用户权限处理
 * 
 * @author ht
 */
@Component
@Slf4j
public class SysPermissionService
{
    @Autowired
    @Qualifier("SysRoleServiceImpl")
    private ISysRoleService roleService;

    @Autowired
    @Qualifier("sysMenuServiceImpl")
    private ISysMenuService menuService;

    @Autowired
    private QsConfig qsConfig;

    /**
     * 获取角色数据权限
     * 
     * @param user 用户信息
     * @return 角色权限信息
     */
    public Set<String> getRolePermission(SysUser user)
    {
        Set<String> roles = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            roles.add("admin");
        }
        else
        {
            roles.addAll(roleService.selectRolePermissionByUserId(user.getUserId()));
        }
        return roles;
    }

    /**
     * 获取菜单数据权限
     * 
     * @param user 用户信息
     * @return 菜单权限信息
     */
    public Set<String> getMenuPermission(SysUser user)
    {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin())
        {
            perms.add("*:*:*");
        }
        else
        {
            List<SysRole> roles = user.getRoles();
            if (!CollectionUtils.isEmpty(roles))
            {
                // 多角色设置permissions属性，以便数据权限匹配权限
                for (SysRole role : roles)
                {
                    Set<String> rolePerms = menuService.selectMenuPermsByRoleId(role.getRoleId());
                    role.setPermissions(rolePerms);
                    perms.addAll(rolePerms);
                }
            }
            else
            {
                perms.addAll(menuService.selectMenuPermsByUserId(user.getUserId()));
            }
        }
        return perms;
    }


    public Set<String> getMenuPermission(QsUser user)
    {
        Set<String> perms = new HashSet<String>();
        // 管理员拥有所有权限
        if (user.isAdmin()) {
            perms.add("*:*:*");
        } else {
            try {
                QsApi api = QsApi.getApi();
                List<String> authentication = api.authentication(user.getUid());

                log.info("api====={}",api);
                log.info("当前用户获取的authentication====={}",authentication);

                Set<String> set = menuService.selectMenuPermsByAuthCodeList(authentication);
                if (CollectionUtils.isEmpty(set)) {
                    perms.add("*:*:*");
                } else {
                    perms.addAll(set);
                }
            } catch (Exception e) {
                e.printStackTrace();
                log.info("请求qs异常====={}",e.getMessage());
                throw new RuntimeException(e);
            }
        }
        return perms;
    }

    public Set<String> getRolePermission(QsUser qsUser) {
        if (qsUser.isAdmin()) {
            return new HashSet<String>(){{add("admin");}};
        }else {
            //根据uid、ouid查询角色  todo

            ParentRoles parentRoles = findPersonRoles(qsUser.getUid(), qsUser.getOuid());
            if (StringUtils.isNotNull(parentRoles))
            {
                Roles roles = parentRoles.getRoles();
                if (StringUtils.isNotNull(roles))
                {
                    List<Role> roleList = roles.getRoleList();
                    if (StringUtils.isNotEmpty(roleList))
                    {
                        //如果
                        //todo
                    }
                    for (Role role : roleList) {
                        //根据id查找角色
//                        QsApi api = QsClientUtil.init();
                        System.out.println("role====="+role.toString());
                    }
                }
            }
            return new HashSet<String>(){{add("admin");}};
        }
    }


    /**
     * 查询所有角色
     */
    public ParentRoles findPersonRoles(String uid,String ouid) {

        String serverUrl = qsConfig.getServerUrl();
        String service = serverUrl + "service/findRoleByUid";

        Map<String, String> params = new HashMap();
        params.put("uid", BasecodeUtil.enString(uid));
        params.put("ouid", ouid);
        Document doc = this.getDoc(service, RequestMethod.GET, params);
        XStream xstream = new XStream(new DomDriver());
        xstream.allowTypesByWildcard(new String[]{"cn.microvideo.qsc.client.**"});
        xstream.alias("info", ParentRoles.class);
        xstream.autodetectAnnotations(true);
        try {
            if (Objects.isNull(doc)){
                return null;
            }
            ParentRoles info = (ParentRoles)xstream.fromXML(doc.asXML());
            return info;
        } catch (Exception e) {
            log.error("get person role error", e);
            return null;
        }

    }

    public Document getDoc(String service, RequestMethod method, Map<String, String> params) {
        InputStream in = InputStreamHelper.getInputStream(service, method, params, "");
        Document doc = SAXHelper.getDocument(in);
        return doc;
    }

}
